import { useState, useEffect } from 'react'
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Switch } from '@/components/ui/switch'
import { Loading } from '@/components/ui/loading'
import { Empty } from '@/components/ui/empty'
import type { ModItem, ModList } from '@/types/game'

type TableColumn = {
  name: string
  dataIndex: string
  width?: number
  align?: 'left' | 'center' | 'right' | 'justify' | 'char'
  colSpan?: number
  rowSpan?: number
  header?: () => JSX.Element
  cell?: ({ text, record, index }: {
    text: unknown,
    record: unknown,
    index: number
  }) => JSX.Element
}

type TableColumns = TableColumn[]

const Home = (): JSX.Element => {

  const [tableData, setTableData] = useState<ModList>([])
  const [loading, setLoading] = useState<boolean>(true)

  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = (): void => {
    fetch('/mock/mod-list.json').then((res) => res.json()).then((res) => {
      setTimeout(() => {
        // 模拟网络延迟
        setTableData(res)
        setLoading(false)
      }, 2000)
    })
  }

  const handleModEnabledChange = (record: ModItem, index: number): void => {
    const newData = [...tableData]
    newData[index].enabled = !newData[index].enabled
    setTableData(newData)
  }

  const handleEnabledAllMod = (): void => {
    const newData = [...tableData]
    const enabled = !tableData.every((item) => item.enabled)
    newData.forEach((item) => {
      item.enabled = enabled // 如果所有项都为true，则设置为false，否则设置为true
    })
    setTableData(newData)
  }

  const columns: TableColumns = [
    {
      name: 'enabled',
      dataIndex: 'enabled',
      align: 'center',
      width: 80,
      header: () => {
        return <span className='flex justify-center items-center'>
          <Switch checked={(tableData.length > 0 && tableData.every((item) => item.enabled))} onClick={handleEnabledAllMod} />
        </span>
      },
      cell: ({ text, record, index }) => {
        return <span className='flex justify-center items-center'>
          <Switch checked={text as boolean} onClick={() => handleModEnabledChange(record as ModItem, index)} />
        </span>
      }
    },
    { name: 'name', width: 140, dataIndex: 'name' },
    { name: 'author', width: 140, dataIndex: 'author', align: 'center' },
    { name: 'version', width: 80, dataIndex: 'version', align: 'center' },
    { name: 'description', width: 220, dataIndex: 'description' },
    { name: 'images', dataIndex: 'images', align: 'center' },
  ] as const

  return <div className='home-page'>
    <Table className='shadow-sm rounded-xl inset-shadow-2xs'>
      <TableHeader>
        <TableRow className='h-[40px]'>
          {columns.map((column) => {
            return <TableHead
              key={column.dataIndex}
              className={`${column.width ? `w-[${column.width}px]` : ''} ${column.align ? `text-${column.align}` : ''}`}
              colSpan={column.colSpan}
            >{column.header ? column.header() : column.name}</TableHead>
          })}
        </TableRow>
      </TableHeader>
      <TableBody>
        {
          tableData.length === 0 ?
            <>
              <TableRow className='border-b-0'>
                <TableCell colSpan={columns.length} className="text-center h-[200px]">
                  {loading ? <Loading /> : <Empty />}
                </TableCell>
              </TableRow>
              <TableRow>
                {columns.map((column) => {
                  return <TableCell
                    className="p-0"
                    key={column.dataIndex}
                    align={column.align}
                    width={column.width}
                  >
                  </TableCell>
                })}
              </TableRow>
            </> :
            tableData.map((item, index) => {
              return <TableRow className='h-[40px]' key={item.id}>
                {columns.map((column) => {
                  return <TableCell
                    className="font-medium"
                    key={String(index) + column.dataIndex}
                    align={column.align}
                    width={column.width}
                  >
                    {column.cell ? column.cell({
                      text: item[column.dataIndex],
                      record: item,
                      index: index
                    }) : item[column.dataIndex]}
                  </TableCell>
                })}
              </TableRow>
            })
        }
      </TableBody>
    </Table>
  </div>

}

export default Home
